myApp.controller('barrierController', function ($scope, $rootScope, $uibModal, $stateParams, $http, ngDialog, $interval) {
    $scope.info = {};

    //选中的tab页
    $scope.info.index = 0;
    //全部zone列表
    $scope.info.zones = [];
    //环境列表
    $scope.info.env = uBarrierEnv;
    //当前选中的环境
    $scope.info.env_name = $scope.info.env[0];
    //查询入口信息时 是否包括app列表
    $scope.info.hasApp = false;
    //查询返回入口列表
    $scope.info.entrances = [];
    //是否授权生产发布
    $scope.info.isAuthorize = false;

    //tab 1参数 start
    //当前选中的zone
    $scope.info.selectZone = {};
    //tab 1参数 end

    //tab 2参数 start
    //选中的zone_code列表
    $scope.info.selectZoneCodes = null;
    //选中的1级zone列表
    $scope.info.selectParentZoneCodes = "";
    //选中的2级zone列表
    $scope.info.selectChildZoneCodes = "";
    //显示的二级zone列表
    $scope.info.child_zones = [];
    //全部入口列表
    $scope.info.allTypes = uBarrier_types;
    //选中的入口
    $scope.info.selectType = null;

    //tab 2参数 end

    //tab 3参数 start
    //tab 3参数 end

    //定时器
    $scope.timer = null;
    $scope.authorizeTimer = null;
    $scope.checkStatusTimer = null;

    $scope.$on("$destroy", function () {
        $scope.cleanTimer(true);
    });

    $scope.cleanTimer = function (flag) {
        console.log("清除项目定时器;");
        if ($scope.timer != null) {
            $interval.cancel($scope.timer);
            $scope.timer = null;
        }
        if (flag && $scope.authorizeTimer != null) {
            $interval.cancel($scope.authorizeTimer);
            $scope.authorizeTimer = null;
        }
        if ($scope.checkStatusTimer != null) {
            $interval.cancel($scope.checkStatusTimer);
            $scope.checkStatusTimer = null;
        }
    };

    $scope.getAuthorize = function () {
        $.ajax({
            type: "post",
            url: java_url + "/beetle/deploy/getAuthorize",
            data: {tokenId: getTokenId()},
            dataType: "JSON",
            async: true,
            success: function (data) {
                $scope.info.isAuthorize = data.data.authorize;
            },
            complete: function (xhr, status) {
            }
        });
    };

    $scope.startAuthorizeTimer = function () {
        if ($scope.info.env_name == 'online' && $scope.authorizeTimer == null) {
            $scope.getAuthorize();
            $scope.authorizeTimer = $interval(function () {
                $scope.getAuthorize();
            }, 3000);
        }
        if ($scope.info.env_name != 'online' && $scope.authorizeTimer != null) {
            $interval.cancel($scope.authorizeTimer);
        }
    };
    $scope.startAuthorizeTimer();

    //按钮是否可操作
    $scope.btnPower = function () {
        //1、用户角色包括ubarrier才能操作
        if (!arrayContains(getUserRole(), 'ubarrier_admin')) {
            return false;
        }
        //2、生产环境需要授权
        if ($scope.info.env_name == 'online') {
            if (!$scope.info.isAuthorize) {
                return false;
            }
        }
        return true;
    };

    //根据状态判断按钮是否可点
    //gray online
    $scope.btnShowByStatus = function (entrance) {

        var obj = {};
        obj.gray = false;
        obj.online = false;
        if (entrance.is_overtime == '0') {
            obj.online = true;
            return obj;
        }
        if (entrance.current_status == 'DOING') {
            return obj;
        }
        if ($scope.info.selectZone.check_status == 'READY') {
            obj.gray = true;
            obj.online = true;
            return obj;
        }
        return obj;
    };

    //校验按钮  只有在doing不超时时  不可点  其他情况下都可点
    $scope.validateShowByStatus = function () {
        if ($scope.info.selectZone.current_status != 'DOING') {
            return true;
        }
        var flag = true;

        for (var i in $scope.info.entrances) {
            var entrance = $scope.info.entrances[i];
            if (entrance.current_status == 'DOING' && entrance.is_overtime == '1') {
                flag = flag && false;
            } else {
                flag = flag && true;
            }
        }
        return flag;
    };

    $scope.entrance = function () {
        var url = uBarrier_url + '/entrance/?env_name=' + $scope.info.env_name + '&hasApp=' + $scope.info.hasApp;
        if ($scope.info.selectZoneCodes != "") {
            url += '&zone_codes=' + $scope.info.selectZoneCodes;
        }
        if ($scope.info.selectType != null) {
            url += '&types=' + $scope.info.selectType;
        }
        ;

        doBeetleGet($http, $uibModal, url, function (data) {
            if (data.success) {
                if ($scope.info.hasApp) {
                    $scope.info.entrances = data.data;
                } else {
                    $scope.info.entrances = [];
                    angular.forEach(data.data, function (data) {
                        if ($scope.info.entrances.length == 0) {
                            $scope.info.entrances.push(data)
                        } else {
                            var count = 0;
                            angular.forEach($scope.info.entrances, function (entrance) {
                                if (entrance.type == data.type) {
                                    count = 1;
                                    if (entrance.current_status != data.current_status) {
                                        if (entrance.current_status == "DOING" || data.current_status == 'DOING') {
                                            entrance.current_status = "DOING";
                                        } else if (entrance.current_status == 'OUT_OF_SERVICE' || data.current_status == 'OUT_OF_SERVICE') {
                                            entrance.current_status = 'OUT_OF_SERVICE';
                                        }
                                    }
                                }
                            });
                            if (count == 0) {
                                $scope.info.entrances.push(data)
                            }
                        }
                    })
                }
                if ($scope.info.selectZone.current_status == 'DOING') {
                    $scope.interval();
                }
            } else {
                alert(data.msg);
            }
        });
    };

    $scope.intervalEntrance = function () {
        $http.get(uBarrier_url + '/entrance/?env_name=' + $scope.info.env_name + '&zone_codes=' + $scope.info.selectZoneCodes + '&hasApp=' + $scope.info.hasApp).success(function (data) {
            if (data.success) {
                if ($scope.info.hasApp) {
                    $scope.info.entrances = data.data;
                } else {
                    $scope.info.entrances = [];
                    angular.forEach(data.data, function (data) {
                        if ($scope.info.entrances.length == 0) {
                            $scope.info.entrances.push(data)
                        } else {
                            var count = 0;
                            angular.forEach($scope.info.entrances, function (entrance) {
                                if (entrance.type == data.type) {
                                    count = 1;
                                    if (entrance.current_status != data.current_status) {
                                        if (entrance.current_status == "DOING" || data.current_status == 'DOING') {

                                            entrance.current_status = "DOING";
                                        } else if (entrance.current_status == 'OUT_OF_SERVICE' || data.current_status == 'OUT_OF_SERVICE') {

                                            entrance.current_status = 'OUT_OF_SERVICE';
                                        }
                                    }
                                }
                            });
                            if (count == 0) {
                                $scope.info.entrances.push(data);
                            }
                        }
                    })
                }
                var flag = true;

                for (var i in data.data) {
                    var entrance = data.data[i];
                    if (entrance.current_status == 'DOING') {
                        flag = flag && false;
                    } else {
                        flag = flag && true;
                    }
                }

                if ($scope.info.selectZone.current_status != "DOING" && flag) {
                    $scope.cleanTimer(false);
                }
            } else {
                alert(data.msg);
            }
        })

    };
    $scope.intervalZones = function () {
        $http.get(uBarrier_url + '/zones/?env_name=' + $scope.info.env_name).success(function (data) {
            if (data.success) {
                $scope.info.zones = data.data;
                if ($scope.info.selectZoneCodes == null) {
                    $scope.info.selectZone = data.data[0];
                    $scope.info.selectZoneCodes = $scope.info.selectZone.zone_code;
                } else {
                    angular.forEach(data.data, function (zone) {
                        zone.check = false;
                        if (zone.zone_code == $scope.info.selectZoneCodes) {
                            zone.check = true;
                            $scope.info.selectZone = zone;
                        }
                    })
                }
            } else {
                alert(data.msg);
            }
        })
    };

    $scope.Initialization = function () {
        $.ajax({
            type: "GET",
            url: uBarrier_url + '/zones/?env_name=' + $scope.info.env_name,
            async: false,
            success: function (data) {
                if (data.success) {
                    $scope.info.zones = data.data;
                } else {
                    alert(data.msg)
                }
            }
        });
        if ($scope.info.selectZoneCodes == null) {
            $scope.info.selectZone = $scope.info.zones[0];
            $scope.info.selectZoneCodes = $scope.info.selectZone.zone_code;
        } else {
            angular.forEach($scope.info.zones, function (zone) {
                zone.check = false;
                if (zone.zone_code == $scope.info.selectZoneCodes) {
                    zone.check = true;
                    if (zone.current_status == 'DOING') {
                    }
                    $scope.info.selectZone = zone;
                }
            })
        }
    };

    // $scope.OperateGroupGNONE = function () {
    //     var istrue = false;
    //
    //     if ($scope.info.selectZone.operate_group == 'NONE') {
    //         istrue = true
    //     }
    //     if (!istrue) {
    //         angular.forEach($scope.info.entrances, function (entrance) {
    //             if (entrance.current_status != 'GNONE' && entrance.current_status != 'READY') {
    //                 istrue = true;
    //             }
    //         })
    //     }
    //     return istrue;
    // };

    $scope.showMsg = function (data) {
        var msgstr = "";
        var cl = "";
        if (data.current_status == 'GA') {
            msgstr = "A组灰度";
            cl = "GAMsg";
        }
        if (data.current_status == 'GB') {
            msgstr = "B组灰度";
            cl = "GAMsg";
        }
        if (data.current_status == 'DOING') {
            if ($scope.info.selectZone.expect_status == 'READY') {
                msgstr = "检查状态中";
                cl = "DOINGMsg";
            } else {
                if ($scope.info.selectZone.expect_status == 'GNONE') {
                    msgstr = "切换线上中";
                } else if ($scope.info.selectZone.expect_status == 'GA') {
                    msgstr = "A组切换中";
                } else if ($scope.info.selectZone.expect_status == 'GB') {
                    msgstr = "B组切换中";
                }
                cl = "DOINGMsg";
            }
        }
        if (data.current_status == 'OUT_OF_SERVICE') {
            if ($scope.info.selectZone.expect_status == 'READY') {
                msgstr = "检查状态异常";
                cl = "OUT_OF_SERVICEMsg";
            } else {
                if ($scope.info.selectZone.expect_status == 'GNONE') {
                    msgstr = "切换线上异常";
                } else if ($scope.info.selectZone.expect_status == 'GA') {
                    msgstr = "A组切换异常";
                } else if ($scope.info.selectZone.expect_status == 'GB') {
                    msgstr = "B组切换异常";
                }
                cl = "OUT_OF_SERVICEMsg";
            }
        }

        if (data.current_status == 'READY') {
            msgstr = "检查状态通过";
            cl = "READYMsg";
        }

        if (data.current_status == 'GNONE') {
            msgstr = "生产";
            cl = "GNONEMsg";
        }

        data.msg = msgstr;
        data.class = cl;
        return data;
    };


    $scope.check = function () {
        if (!$scope.btnPower()) {
            alert("没有访问权限，请联系管理员！");
            return;
        }

        openDialog(ngDialog, $scope, "确认要检查当前区域?", true, function (val) {
            if (!val) {
                return;
            }

            doBeetleGet($http, $uibModal, uBarrier_url + '/switch/check?token_id=' + getTokenId() + '&env_name=' + $scope.info.env_name + '&zone_code=' + $scope.info.selectZoneCodes, function (data) {
                if (data.success) {
                    $scope.interval();
                } else {
                    alert(data.msg);
                }
            });
        });
    };


    //校验环境下所有资源状态
    $scope.checkAllZone = function () {
        if (!$scope.btnPower()) {
            alert("没有访问权限，请联系管理员！");
            return;
        }

        openDialog(ngDialog, $scope, "确认要检查所有区域?", true, function (val) {
            if (!val) {
                return;
            }
            angular.forEach($scope.info.zones, function (zone) {
                if (zone.parent_code != null) {
                    return;
                }
                zone.checkStatus = false;

                doBeetleGet($http, $uibModal, uBarrier_url + '/switch/check?token_id=' + getTokenId() + '&env_name=' + $scope.info.env_name + '&zone_code=' + zone.zone_code, function (data) {
                    if (data.success) {
                        $scope.startCheckStatusTimer();
                        zone.checkStatus = true;
                    } else {
                        zone.checkMsg = data.msg;
                    }
                });
            });
        });
    };
    $scope.info.errorAppList = [];
    $scope.info.errorEntranceList = [];
    $scope.getErrorList = function () {
        $http.get(uBarrier_url + '/apps/?token_id=' + getTokenId() + '&current_status=OUT_OF_SERVICE,DOING&is_resource=0&env_name=' + $scope.info.env_name).success(function (data) {
            $scope.info.errorAppList = data.data;
            $http.get(uBarrier_url + '/entrance/?token_id=' + getTokenId() + '&current_status=OUT_OF_SERVICE,DOING&env_name=' + $scope.info.env_name).success(function (d) {
                $scope.info.errorEntranceList = d.data;
            })
        })
    };
    $scope.startCheckStatusTimer = function () {
        if ($scope.checkStatusTimer == null) {
            $scope.getErrorList();
            $scope.checkStatusTimer = $interval(function () {
                $scope.getErrorList();
            }, 3000);
        }
    };

    $scope.showStatus = function (group, i) {
        // if ($scope.info.selectZone.expect_status == 'READY' && $scope.info.selectZone.operate_group == 'NONE') {
        //     return i.current_status;
        // }
        // ;
        // if (group != $scope.info.selectZone.operate_group) {
        //     return 'GNONE';
        // }
        return i.current_status;
    };

    // $scope.updateOperateGroup = function (status) {
    //     if (!$scope.btnPower()) {
    //         alert("没有访问权限，请联系管理员！");
    //         return;
    //     }
    //     var msg = "";
    //     if (status == 'A') {
    //         msg = "开始操作A组"
    //     } else if (status == 'B') {
    //         msg = "开始操作B组"
    //     } else {
    //         msg = "操作完成"
    //     }
    //     openDialog(ngDialog, $scope, msg + "，请确认！", true, function (val) {
    //         if (!val) {
    //             return;
    //         }
    //
    //         doBeetlePost($http, $uibModal, uBarrier_url + '/zones/updateOperateGroup', {
    //             operate_group: status,
    //             zone_code: $scope.info.selectZoneCodes,
    //             token_id: getTokenId(),
    //             env_name: $scope.info.env_name
    //         }, function (data) {
    //             if (data.success) {
    //                 $scope.title(0, null);
    //             } else {
    //                 alert(data.msg)
    //             }
    //         });
    //     })
    // };

    //批量切换
    $scope.Operation = function (i, status) {
        if (!$scope.btnPower()) {
            alert("没有访问权限，请联系管理员！");
            return;
        }

        var url = uBarrier_url + '/switch/?env_name=' + $scope.info.env_name + '&token_id=' + getTokenId() + '&zone_code=' + $scope.info.selectZoneCodes + "&status=" + status;
        if ($scope.info.index == 0) {
            url += "&entrance_types=" + i.type;
        } else {
            url += "&app_name=" + i.app_name;
        }

        var stamsg = "";
        if (status == 'GA') {
            stamsg = "A组灰度";
        } else if (status == 'GB') {
            stamsg = "B组灰度";
        } else if (status == 'GNONE') {
            stamsg = "线上";
        }

        openDialog(ngDialog, $scope, "是否切换" + i.prefix + "到" + stamsg + "状态，请确认！", true, function (val) {
            if (!val) {
                return;
            }
            openDialog(ngDialog, $scope, "请再次确认，是否切换" + i.prefix + "到" + stamsg + "状态?", true, function (val) {
                if (!val) {
                    return;
                }
                doBeetleGet($http, $uibModal, url, function (data) {
                    if (data.success) {
                        $scope.title(0, null);
                        $scope.interval();
                    } else {
                        alert(data.msg);
                    }
                })

            });
        })
    };

    //创建定时器
    $scope.interval = function () {
        if ($scope.timer == null) {
            $scope.intervalZones();
            $scope.intervalEntrance();
            $scope.timer = $interval(function () {
                $scope.intervalZones();
                $scope.intervalEntrance();
            }, 3000);
        }
    };

    //tab2 入口选择
    $scope.clickType = function () {
        $scope.info.selectType = null;
        angular.forEach($scope.info.allTypes, function (type) {
            if (type.check) {
                $scope.info.selectType += type.type + ',';
            }
        });
        if ($scope.info.selectType != null) {
            $scope.info.selectType = $scope.info.selectType.substr(0, $scope.info.selectType.length - 1)
        }
        $scope.entrance();
    };

    $scope.selectParentZone = function () {
        $scope.info.selectParentZoneCodes = "";
        $scope.info.child_zones = [];
        angular.forEach($scope.info.zones, function (zone) {
            if (zone.check) {
                $scope.info.selectParentZoneCodes += zone.zone_code + ',';
                angular.forEach($scope.info.zones, function (sec_zone) {
                    if (zone.zone_code == sec_zone.parent_code) {
                        $scope.info.child_zones.push(sec_zone);
                    }
                })
            }
        });
        if ($scope.info.child_zones.length == 0) {
            $scope.info.selectParentZoneCodes = "";
            $scope.info.selectChildZoneCodes = "";
            angular.forEach($scope.info.zones, function (data) {
                data.check = false;
            })
        }
        $scope.info.selectParentZoneCodes = $scope.info.selectParentZoneCodes.substr(0, $scope.info.selectParentZoneCodes.length - 1);
        $scope.getSelectZones();
    };

    $scope.showError = function (i, group) {
        var info = {};
        info = i;
        info.current_group = group;
        var modalInstance = $uibModal.open({
            animation: true,
            templateUrl: 'showError.html',
            controller: 'showErrorCtrl',
            resolve: {
                info: function () {
                    return info;
                }
            }
        });
    };

    $scope.selectChildZone = function () {
        $scope.info.selectChildZoneCodes = "";
        angular.forEach($scope.info.child_zones, function (zone) {
            if (zone.check) {
                $scope.info.selectChildZoneCodes += zone.zone_code + ',';
            }
        });
        $scope.info.selectChildZoneCodes = $scope.info.selectChildZoneCodes.substr(0, $scope.info.selectChildZoneCodes.length - 1);
        $scope.getSelectZones();
    };
    $scope.getSelectZones = function () {
        $scope.info.selectZoneCodes = $scope.info.selectParentZoneCodes;
        if ($scope.info.selectChildZoneCodes != '') {
            $scope.info.selectZoneCodes += ',' + $scope.info.selectChildZoneCodes;
        }
        $scope.entrance();
    };

    $scope.title = function (index, type) {
        $scope.info.index = index;
        if (type == null) {
            $scope.info.selectType = null;
        } else {
            $scope.info.selectType = type;
        }
        $scope.cleanTimer(false);
        $scope.Initialization();
        if (index == 0) {
            $scope.info.hasApp = false;
            $scope.startAuthorizeTimer();
            if ($scope.info.selectZone.current_status == 'DOING') {
                $scope.interval();
            }
            $scope.entrance();
        } else if (index == 1) {
            $scope.info.hasApp = true;
            angular.forEach($scope.info.allTypes, function (type) {
                if ($scope.info.selectType == type.type) {
                    types.check = true;
                } else {
                    type.check = false;
                }
            });
            angular.forEach($scope.info.zones, function (zone) {
                if ($scope.info.selectZoneCodes == zone.zone_code) {
                    zone.check = true;
                    $scope.selectParentZone();
                }
            })
        } else if (index == 2) {
            $scope.info.errorAppList = [];
            $scope.info.errorEntranceList = [];
            angular.forEach($scope.info.zones, function (zone) {
                if (zone.expect_status == 'READY') {
                    zone.checkStatus = true;
                    $scope.startCheckStatusTimer();
                }
            });
        } else {
        }
    };
    $scope.title(0, null);
    $scope.regionTitle = function (regionIndex) {
        $scope.cleanTimer(false);
        $scope.info.selectZone = regionIndex;
        $scope.info.selectZoneCodes = regionIndex.zone_code;
        $scope.entrance();
    };

    $scope.selectError = function (app) {
        var info = {};
        info = app;
        var modalInstance = $uibModal.open({
            animation: true,
            templateUrl: 'error.html',
            controller: 'errorCtrl',
            resolve: {
                info: function () {
                    return info;
                }
            }
        });
    }
});

myApp.controller('showErrorCtrl', function ($scope, $uibModal, $uibModalInstance, info, $http) {
    $scope.info = info;
    $scope.info.appList = [];
    $scope.total = $scope.info.appList.length;

    $scope.page = {size: 15, index: 1};

    if ($scope.info.type == 'jmx' || $scope.info.type == 'hosts') {
        $http.get(uBarrier_url + '/apps/?env_name=' + $scope.info.env_name + '&entrance_types=' + $scope.info.type + '&current_status=OUT_OF_SERVICE&is_resource=0&zone_code=' + $scope.info.zone_code + '&group=' + $scope.info.current_group).success(function (data) {
            if (data.success) {
                $scope.info.appList = data.data;
            } else {
                alert(data.msg);
            }
        });
    } else {
        $scope.info.appList.push($scope.info);
    }

    $scope.selectError = function (app) {
        var info = {};
        info = app;
        var modalInstance = $uibModal.open({
            animation: true,
            templateUrl: 'error.html',
            controller: 'errorCtrl',
            resolve: {
                info: function () {
                    return info;
                }
            }
        });
    };
    $scope.cancel = function () {
        // 关闭弹出框
        $uibModalInstance.dismiss('cancel');
    };

});

myApp.controller('errorCtrl', function ($scope, $uibModalInstance, info, $http) {
    $scope.info = {};
    $scope.info.msg = "";
    if (info.error_desc != null) {
        $scope.info.msg = info.error_desc;
    } else {
        var str = "";
        if (info.expect_status == "GA") {
            str = "A组进入灰度"
        } else if (info.expect_status == "GB") {
            str = "B组进入灰度"
        } else if (info.expect_status == "GNONE") {
            str = "恢复生产"
        } else if (info.expect_status == "READY") {
            str = "校验状态"
        }

        $scope.info.msg = "切换状态异常，当前状态:" + info.current_status + ",期望状态:" + str;
    }

    $scope.cancel = function () {
        // 关闭弹出框
        $uibModalInstance.dismiss('cancel');
    };
});